package com.xiaogao.common.config.mybatisplus.interceptor;


import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.xiaogao.common.utils.token.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

@RequiredArgsConstructor
@Slf4j
@Component
public class DataScopeInterceptor implements InnerInterceptor {
    private final HttpServletRequest request;

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter,
                            RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
        String originalSql = boundSql.getSql();
        if (originalSql.contains("sqlText")) {
            // 1、获取当前登录用户，拿到用户的dataScope值【userId_username】
            String token = request.getHeader("token");
            Claims claims = JwtUtils.parse(token);
            String userId = String.valueOf(claims.get("userId"));
            String deptId = String.valueOf(claims.get("deptId"));
            String dataScopes = String.valueOf(claims.get("dataScopes"));
            log.info("dataScopes={}",dataScopes);
            // 4、根据dataScope的值拼接不同的sql
            String newSql;
            if (dataScopes.contains("3")) { // 所有
                newSql = originalSql.replace("sqlText", " ");
            } else if (dataScopes.contains("2")) { // 部门
                newSql = originalSql.replace("sqlText", " and dept_id = " + deptId);
            } else { // 个人  表某个人的数据 --- and owner_id = xxx
                newSql = originalSql.replace("sqlText", " and su.id = " + userId);
            }
            // newSql 重新赋值给boundSql
            log.info("originalSql={},newSql={}", originalSql, newSql);

            // 使用 MyBatis 的 MetaObject 修改 SQL
            MetaObject metaObject = SystemMetaObject.forObject(boundSql);
            metaObject.setValue("sql", newSql);
        }
    }
}
